package org.evej.apiparser.parser.handler.character;

import org.evej.apiparser.model.character.ApiAsset;
import org.evej.apiparser.model.character.ApiAssetContainer;
import org.evej.apiparser.parser.handler.ApiDocumentHandler;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public class AssetsHandler extends ApiDocumentHandler<ApiAssetContainer> {

    private ApiAssetContainer.Builder currentContainerBuilder;
    private long itemID;
    private int typeID;
    private long quantity;
    private long locationID;
    private int flag;
    private boolean isPreviousEndtagRowset = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
        if ("row".equals(qName)) {
            itemID = attributeToLong(attrs, "itemID");
            typeID = attributeToInt(attrs, "typeID");
            quantity = attributeToLong(attrs, "quantity");
            flag = attributeToInt(attrs, "flag");
            if (attrs.getValue("locationID") != null) {
                locationID = attributeToLong(attrs, "locationID");
            }
        } else if ("rowset".equals(qName)) {
            if (currentContainerBuilder == null) {
                currentContainerBuilder = new ApiAssetContainer.Builder();
            } else {
                ApiAssetContainer.Builder container = new ApiAssetContainer.Builder(currentContainerBuilder, itemID, typeID, quantity, locationID, flag);
                currentContainerBuilder = container;
            }
        }
        super.startElement(uri, localName, qName, attrs);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ("rowset".equals(qName)) {
            if (currentContainerBuilder.getParent() != null) {
                currentContainerBuilder.getParent().addAsset(currentContainerBuilder.build());
                currentContainerBuilder = currentContainerBuilder.getParent();
            }
            isPreviousEndtagRowset = true;
        } else if ("row".equals(qName) && !isPreviousEndtagRowset) {
            currentContainerBuilder.addAsset(new ApiAsset(itemID, typeID, quantity, locationID, flag));
            isPreviousEndtagRowset = false;
        } else {
            isPreviousEndtagRowset = false;
        }
        super.endElement(uri, localName, qName);
    }

    @Override
    public void endDocument() throws SAXException {
        super.documentModel = currentContainerBuilder.build();
        super.endDocument();
    }

}
